<template>
  <view class="activity-participate-confirm-page">
    <view style="height:400rpx;background-color: #ea2327;">

      <view class="u-text-center u-padding-30 u-padding-left-80 u-padding-right-80 u-flex u-row-around"
            style="height:300rpx;color: #FFFFFF;flex-direction: column;">
        <!--      活动名称-->
        <text style="font-size: 40rpx;font-weight: bold;">{{confirmInfo.title}}</text>
        <!--      活动地点-->
        <text class="u-font-sm">{{confirmInfo.address}}</text>

        <!--      活动时间-->
        <text class="u-font-sm">{{confirmInfo.startTime}} - {{confirmInfo.endTime}}</text>
      </view>

    </view>

    <view class="u-flex u-col-center u-row-around u-padding-30"
          style="margin-top: -15rpx;background-color: #FFFFFF;border-radius: 20rpx;min-height: 400rpx;flex-direction: column;">
      <view class="u-text-center">
        <view class="u-margin-bottom-20"><text>活动退款截止时间</text></view>
        <text class="u-light-color"> {{enrollRule.refundDeadline || '暂无'}}</text>
      </view>

      <view>
        <text>您需支付：</text>
        <text style="color: #ea2327">{{priceForMe / 100}}元</text>
      </view>

      <view>
        <u-button type="error" @click="participate">确认报名</u-button>
      </view>
    </view>
    <view class="hint">
      <u-checkbox v-model="agreement" shape="circle" :size="25" :icon-size="15" active-color="#ea2327"></u-checkbox>同意
      <text class="link" @tap="activityProtocol">《 活动协议 》</text>
      约定双方职责，以更顺利和进行相关活动
    </view>
  </view>
</template>

<script>
import ActivityUrl from '../../../../pc/ActivityUrl.js'
import wxMpPayTool from "../../../../../../../components/common/web/components/app/wxMpPayTool.js"
export default {
  computed:{
    // 对于我的价格
    priceForMe(){
      if(!this.enrollRule){
        return ''
      }
      let p = {
        'm': this.enrollRule.malePrice,
        'f': this.enrollRule.femalePrice
      }
      if(this.vuex_hasLogin){
        if(this.vuex_userInfo.gender){
          return p[this.vuex_userInfo.gender]
        }
      }

      return ''
    }
  },
  data(){
    return {
      // 上个页面传递过来的活动id
      activityId: '',
      confirmInfo: {
      },
      enrollRule: {},
      // 添加一个标识，标识正在支付中
      payLoading: false,
      agreement: false,
    }
  },
  onLoad(options){
    this.activityId = options.activityId
    this.loadConfirmInfo()
  },

  onReady(){
  },
  methods:{
    activityProtocol(){
      this.$u.route('/pages/common/richText?code=activity_protocol&title=活动协议')
    },
    // 加载确认数据
    loadConfirmInfo(){
      let url = this.$stStringTools.replaceb(ActivityUrl.activityParticipateConfirmInfo,{id:this.activityId})
      this.$http.get(url).then(res => {
        this.enrollRule = res.data.enrollRule
        this.confirmInfo = res.data
      })
    },
    // 确认报名，点击按钮事件
    participate(){
      if(!this.priceForMe){
        this.$u.toast('未能为您关联到报名费用，可能您的性别信息需要完善')
        return
      }
      // #ifdef H5
      // H5 只能在微信中打开
      if(!this.$stCommonTools.browser.versions.weixin){
        this.$u.toast("抱歉，暂不支持H5平台报名，您可以在微信中打开链接")
        return
      }

      // #endif
      this.createOrder()
    },
    // 下单
    createOrder() {
      if (!this.agreement) {
        uni.showToast({
          title: "请同意相关活动协议后继续",
          icon: 'none'
        })
        return
      }
      let payForm = {}
      //商品描述
      payForm.channelCode = 'wwdH5'
      payForm.title = this.confirmInfo.title
      payForm.description = this.confirmInfo.title
      payForm.totalAmount = this.priceForMe
      // 默认人民币，这里可以不填
      payForm.currencyDictValue = null
      payForm.categoryDictValue = 'wwd_activity'
      payForm.payTypeDictValue = this.enrollRule.isNeedPayOnline ? 'on_line_pay': 'off_line_pay'
      payForm.payChannelDictValue = 'wx_jsapi'

      payForm.goodsForms = [
        {
          id: this.confirmInfo.id,
          name: this.confirmInfo.title,
          count: 1,
          amount: this.priceForMe,
          imageUrl: this.confirmInfo.titleUrl
        }
      ]

      payForm.mpAppCode = this.$config.mpAppCode

      // 支付中
      if (this.payLoading){
        this.$u.toast('处理中，请稍候')
        return
      }

      this.payLoading = true
      uni.showLoading({title: '报名中...'})
      this.$http.post('/order/create', payForm).then(response => {
        uni.hideLoading()
        let content = response.data
        if(!this.enrollRule.isNeedPayOnline){
          uni.showToast({
            duration: 3000,
            title: "线下支付报名成功",
            icon: 'none'
          })
        }else {
          this.doPay(content.ext.orderWx.prepayId)
        }
      }).catch(error => {
        uni.showToast({
          duration: 3000,
          icon: 'none',
          title: error.data.errorMsg
        })
        this.payLoading = false
      }).finally(() => {
        uni.hideLoading()
      })
    },
    // 下单成功后调起微信支付弹窗支付
    doPay(prepayId) {

      // #ifdef H5
      if (typeof WeixinJSBridge == "undefined"){
        this.$u.toast('当前运行环境不支持在线支付，请移步微信中打开')
        this.payLoading = false
        return
      }
      // #endif
      let param = {
        appCode: this.$config.mpAppCode,
        prepayId: prepayId,
        payChannelDictValue: 'wx_jsapi'
      }
      this.$http.get('/pay/wx/paySign', {params: param}).then(res => {
        // 调起微信支付
        wxMpPayTool.onBridgeReady(res.data,  (res)=> {

          this.payLoading = false
          let errMsg = res.err_msg || res.errMsg
          if (errMsg == "get_brand_wcpay_request:ok") {
            // 使用以上方式判断前端返回,微信团队郑重提示：
            //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
            uni.showToast({
              duration: 3000,
              title: "支付成功,感谢您的报名",
              icon: 'none'
            })
            setTimeout(()=>{
              // 成功后，返回活动详情
              uni.navigateBack({
                delta: 1
              });
            },1000)
          }else if(errMsg == 'get_brand_wcpay_request:cancel'){
            // 用户取消，调用订单状态接口关闭订单
            this.payLoading = false

            uni.showModal({
              title: '提示',
              content: '您稍候还可以在订单管理中完成支付',
              showCancel: false,
              confirmText: '好的'
            })
          }else if(errMsg == 'chooseWXPay:fail, the permission value is offline verifying'){
            this.$u.toast('调起微信支付失败,请在微信中打开')
          }
        })
      })
          .catch(error => {
            uni.showToast({
              icon: 'none',
              title: error.data.errorMsg
            })
          }).finally(()=>{
        this.payLoading = false
      })
    },
  }
}
</script>

<style lang="scss" scoped>

.hint {
  padding: 20rpx 40rpx;
  font-size: 20rpx;
  color: $u-tips-color;

  .link {
    color: $u-type-warning;
  }
}
</style>